<template>
    <el-dialog :title="title" v-model="open" width="500px">
        <el-form :model="formItem" label-width="auto">
            <el-form-item label="等级名称">
                <el-input v-model="formItem.name" />
            </el-form-item>
            <el-form-item label="等级">
                <el-input v-model="formItem.grade" />
            </el-form-item>
            <el-form-item label="享受折扣">
                <el-input v-model="formItem.discount" />
            </el-form-item>
            <el-form-item label="解锁经验值">
                <el-input v-model="formItem.exp" />
            </el-form-item>
            <el-form-item label="图标">
                <!-- import.meta.env.VITE_BASE_URL -->
                <el-upload class="avatar-uploader" :action="`${baseURL}/image/upload`" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <!-- 当有图片时，渲染图片 -->
                    <img v-if="formItem.icon" :src="formItem.icon" class="avatar" />
                    <!-- 当没有图片，就显示图标 -->
                    <el-icon v-else class="avatar-uploader-icon">
                        <Picture />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户等级背景">
                <!-- import.meta.env.VITE_BASE_URL -->
                <el-upload class="avatar-uploader" :action="`${baseURL}/image/upload`" :show-file-list="false"
                    name="file" :on-success="handleBgImageSuccess">
                    <!-- 当有图片时，渲染图片 -->
                    <img v-if="formItem.bg_image" :src="formItem.bg_image" class="avatar" />
                    <!-- 当没有图片，就显示图标 -->
                    <el-icon v-else class="avatar-uploader-icon">
                        <Picture />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="是否显示">
                <el-radio-group v-model="formItem.is_show">
                    <el-radio :value="1">显示</el-radio>
                    <el-radio :value="0">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="open = false">取消</el-button>
                <el-button type="primary" @click="onConfirm">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    addUserGradeApi, getUserGradeByIdApi, updateUserGradeApi,
    type GradeItemType
} from '@/api/userGrade';
import { computed, ref, watch } from 'vue';
import { Picture } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
const emit = defineEmits(['findUserGrade']);
const open = ref(false);

const baseURL = import.meta.env.VITE_BASE_URL;

// 用于表单内数据的双向绑定（新增或修改的等级对象）
const formItem = ref<GradeItemType>({
    _id: '', is_show: 1, name: '', grade: '', discount: '', exp: ''
});

const title = computed(() => {
    if (formItem.value._id) {
        return '编辑用户等级'
    }
    return '添加用户等级'
})

// 侦听弹窗的打开状态open
watch(open, () => {
    // 当弹窗打开时
    if (open.value && formItem.value._id) {
        getUserGroupById();
    }
})

// 图片上传成功后执行的方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    res
) => {
    if(res.code == 200) {
        formItem.value.icon = res.data;
    }
}
const handleBgImageSuccess: UploadProps['onSuccess'] = (
    res
) => {
    if(res.code == 200) {
        formItem.value.bg_image = res.data;
    }
}

// 点击弹窗的【确认】按钮
function onConfirm() {
    // 如果有_id，说明在修改数据
    if (formItem.value._id) {
        updateUserGroup();
    } else {
        addUserGroup();
    }
}

function addUserGroup() {
    addUserGradeApi(formItem.value).then((res) => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '用户等级添加成功'
            })
            open.value = false;
            // 添加成功后，调用父组件的方法，重新获取最新数据并渲染
            emit('findUserGrade');
        } else {
            ElMessage.error(res.message);
        }
    })
}

function updateUserGroup() {
    updateUserGradeApi(formItem.value)
        .then((res: any) => {
            if (res.code == 200) {
                ElMessage.success('用户等级修改成功');
                open.value = false;
                // 添加成功后，调用父组件的方法，重新获取最新数据并渲染
                emit('findUserGrade');
            } else {
                ElMessage.error(res.message);
            }
        })
}

function getUserGroupById() {
    getUserGradeByIdApi({
        _id: formItem.value._id
    }).then((res: any) => {
        if (res.code == 200) {
            formItem.value = res.data;
        }
    })
}

// 打开弹窗
function openDialog(_id?: string) {
    // 如果父组件传递了_id，说明要做修改
    if (_id) {
        formItem.value._id = _id;
    } else {
        formItem.value = { is_show: 1, name: '', grade: '', discount: '', exp: '' }
    }
    open.value = true;
}

defineExpose({
    openDialog
})

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 60px;
    height: 60px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px solid var(--el-border-color);
    box-shadow: 0px 0px 14px #ccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    text-align: center;
}
</style>